package io.flutter.eventbus;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import org.json.JSONObject;

import java.util.Map;

public class Topic<T> implements MethodChannel.MethodCallHandler{

    protected VoidCall<T> func;

    protected MethodChannel methodChannel;

    protected String name;

    protected boolean isClose = false;

    Topic(MethodChannel methodChannel, String name) {
        this.methodChannel = methodChannel;
        this.name = name;
    }

    public void receive(VoidCall<T> func) {
        this.func = func;
    }

    public void send(T data) {
        methodChannel.invokeMethod(Standard.receive, data);
    }

    public void close() {
        isClose = true;
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        if (!isClose) {
            switch (methodCall.method) {
                case Standard.receive:
                    result.success(Standard.success);
                    if (func != null) {
                        func.call((T)methodCall.arguments);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}

//enum Status{
//    success,
//    failure,
//}
//
class Result<T> implements MethodChannel.Result {

    private VoidCall<T> func;

    Result(VoidCall<T> func){
        this.func = func;
    }

    @Override
    public void success(Object o) {
        func.call((T)o);
    }

    @Override
    public void error(String s, String s1, Object o) {

    }

    @Override
    public void notImplemented() {

    }
}
